package net.linlan.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 *
 * Filename:CorsConfig.java
 * Desc:跨域配置注入类
 *
 * @author Linlan
 * CreateTime:2018/6/6 17:58
 *
 * @version 1.0
 * @since 1.0
 *
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Value("${spring.profiles.active}")
    private String activeMode;
    @Value("${platform.prop.allowedOrigins}")
    private String[] allowedOrigins;

    /**
     * 跨域配置
     */
    @Bean
    public CorsFilter corsFilter()
    {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 可信域配置
        if (allowedOrigins != null && allowedOrigins.length > 0){
            for (String allowedOrigin : allowedOrigins) {
                config.addAllowedOriginPattern(allowedOrigin);
            }
        }else{
            // 设置访问源地址
            config.addAllowedOriginPattern("*");
        }
        // 设置访问源请求头
        config.addAllowedHeader("*");
        // 设置访问源请求方法
        config.addAllowedMethod("*");
        // 有效期 1800秒
        config.setMaxAge(1800L);
        // 添加映射路径，拦截一切请求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        // 返回新的CorsFilter
        return new CorsFilter(source);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        String[] origins = {"*"};
        if (activeMode.contains("prod")
//                || activeMode.contains("test")  //开发调试下，注释，生产发布开启
        ){
            origins = allowedOrigins;
        }
        registry.addMapping("/**")
//                .allowedOrigins(origins)
                .allowedOriginPatterns(origins)
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .maxAge(3600);
    }
}
